use tokio::time;

use crate::{components, dao};
use crate::models::models::components::v2ray::basic_setting::ComponentV2rayBasicSetting;
use crate::models::models::components::v2ray::info::ComponentV2rayState;
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::{Code, MagicBoxResponse};
use crate::runtime::result::MagicBoxResult;

#[tauri::command(rename_all = "snake_case")]
pub(crate) async fn invoke_component_v2ray_save_basic_setting(setting: ComponentV2rayBasicSetting) -> MagicBoxResult<MagicBoxResponse<()>> {
    if setting.http_port == setting.socket_port {
        return Err(MagicBoxError::new(Code::ParameterError, "SOCKS与HTTP端口不能相同"));
    }

    dao::components::v2ray::setting::set_basic_setting(setting)?;

    // 重启服务
    if ComponentV2rayState::Running == components::v2ray::manager::manager().state()? {
        components::v2ray::manager::manager().stop()?;

        time::sleep(time::Duration::from_millis(1000)).await;
        components::v2ray::manager::manager().start()?;
    }

    Ok(MagicBoxResponse::new_empty_success())
}
